package org.mifos.boss.persistence;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.mifos.boss.domainmodel.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;



@Repository(value="userPersistence")
public class UserPersistenceImpl extends BaseBossPersistence implements UserPersistenceInterface {
	
	@Autowired
	private SessionFactory sessionFactory;

	public boolean validateUser(User user){
/*		User tmpUser = (User) sessionFactory.getCurrentSession().load(
				User.class, user.getUserid());
				
		org.hibernate.Query queryResult = sessionFactory.getCurrentSession().createQuery("select userid from UserMaster where userid='" + user.getUserid() + "'");
		List userList = queryResult.list();
*/		
//		List<User> userList =  getHibernateTemplate().find("from UserMaster umaster where umaster.userid = ?", user.getUserid());
//		return (User) sessionFactory.getCurrentSession().createQuery("from UserMaster umaster where umaster.userid = :login")
//	            .setString("login", login).uniqueResult();
//	     User tmpUser = (User) session.createCriteria(User.class).add(Example.create(user));		
		 Session session = sessionFactory.getCurrentSession();

	     User tmpUser = (User) session.createCriteria(User.class)
	                .add(Restrictions.eq("userid", user.getUserid()))
	                .add(Restrictions.eq("password", user.getPassword()))
	                .uniqueResult();

		
		if (tmpUser != null){

			return true;
		}else{
			return false;
		}
	}
	public void addUser(User user) throws HibernateException {
		sessionFactory.getCurrentSession().save(user);
	}
	
	@SuppressWarnings("unchecked")
	public List<User> listUser()  throws HibernateException{
		return sessionFactory.getCurrentSession().createQuery("from User").list();
	}

	public void removeUser(String userID)  throws HibernateException{
		User user = (User) sessionFactory.getCurrentSession().load(
				User.class, userID);
		if (null != user) {
			sessionFactory.getCurrentSession().delete(user);
		}
	}
}
